package com.edroid.apkhooker.home;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.edroid.autorunner.AutoRunActivity;
import com.example.service.SystemServiceGetter;
import com.example.utils.FileUtils;

/**
 * 最近打开应用列表
 * 
 * @author YYichou 2014-04-21
 *
 */
public class RecentAppListFragment extends BaseListFragment {
	private static AppListAdapter mAdapter;
	private static List<AppEntry> mAppList;
	private static PackageManager mPm;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		if(mPm == null) {
			mPm = getActivity().getPackageManager();
			mAppList = new ArrayList<AppEntry>(10);
			mAdapter = new AppListAdapter(getActivity());
			
			load();
		}
		setListAdapter(mAdapter);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v == getListView()) {
			menu.add(4, 4, 4, "从历史记录移除");
		} else {
			super.onCreateContextMenu(menu, v, menuInfo);
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if(item.getGroupId() != 4)
			return false;
		
		final AppEntry appEntry = mAppList.get(pressedIndex);

		switch (item.getItemId()) {
		case 4: {
			mAppList.remove(pressedIndex);
			refresh();
			delaySave();
			break;
		}

		default:
			return super.onContextItemSelected(item);
		}

		return true;
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		final AppEntry appEntry = mAppList.get(position);

		try {
			SystemServiceGetter.getSystemService().watch(appEntry.getPackgeName());
		} catch (Exception e) {
			Toast.makeText(getActivity(), "设置监控失败！", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		
		AutoRunActivity.run(getActivity(), appEntry.getPackgeName());
	}
	
	public void refresh() {
		// Sort the list.
		Collections.sort(mAppList, AppListLoader.ALPHA_COMPARATOR);
		mAdapter.setData(mAppList);
	}
	
	private AppEntry makeAppEntry(String pkg) {
		try {
			ApplicationInfo info = mPm.getApplicationInfo(pkg, 0);
			
			//考虑已卸载

			AppEntry entry = new AppEntry(getActivity(), info);
			entry.loadLabel(getActivity());
			
			return entry;
		} catch (Exception e) {
		}
		
		return null;
	}
	
	public void add(String pkg) {
		for(AppEntry entry : mAppList) {
			if(entry.getPackgeName().equals(pkg))
				return;
		}
		
		mAppList.add(makeAppEntry(pkg));
		refresh();
		delaySave();
	}
	
	public void delaySave() {
		getListView().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				save();
			}
		}, 500);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		save();
	}
	
	private void save() {
		JSONArray tmpArray = new JSONArray();
		for(AppEntry entry : mAppList) {
			tmpArray.put(entry.getPackgeName());
		}
		
		FileUtils.writeStringToFile(getActivity().getFileStreamPath("recentlist.json"),
				tmpArray.toString());
	}
	
	public void load() {
		String str = FileUtils.readFileToString(getActivity().getFileStreamPath("recentlist.json"));
		try {
			JSONArray tmpArray = new JSONArray(str);
			final int N = tmpArray.length();
			
			for(int i=0; i<N; i++) {
				AppEntry entry = makeAppEntry(tmpArray.getString(i));
				if(entry != null)
					mAppList.add(entry);
			}
			
			refresh();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}